package com.estronger.shopmanage.ui.send.pg;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.tasking.DeliverDetailAdpter;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.bean.DeliverDPG;
import com.estronger.shopmanage.bean.DeliverDetail;
import com.estronger.shopmanage.bean.ReturnMsgEntity;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.batchpg.BatchPgActivity;
import com.estronger.shopmanage.utils.ConvertUtils;
import com.estronger.shopmanage.utils.DateUtils;
import com.estronger.shopmanage.utils.JsonUtil;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.PrefUtils;
import com.estronger.shopmanage.utils.ScreenUtils;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.AppDialog;
import com.estronger.shopmanage.view.SelectPeopleActivity;
import com.estronger.shopmanage.view.WiperSwitch;
import com.estronger.shopmanage.view.picker.DateTimePicker;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.Tokens;
import com.soonfor.systemcodes.SystemCodePresenter;
import com.soonfor.systemcodes.SystemCodes;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.jesse.nativelogger.NLogger;

/**
 * （送货）预约派工
 */
public class DeliverAppointmentActivity extends BaseActivity implements View.OnClickListener, WiperSwitch.OnChangedListener {

    private View rl_root;// 根布局view
    private Activity mActivity;
    private TextView deliversname;//客户名称
    private ImageView deliver_phone_call;//客户电话
    private ImageView deliver_send_sms;//客户短信
    private TextView deliver_item_location;//客户住址
    private TextView deliver_dgy;//导购员
    private ImageView deliver_phone_call2;//导购员电话
    private ImageView deliver_send_sms2;//导购员短信
    private TextView kdtime;//开单时间
    private RelativeLayout rlyytime;//预约时间
    private RelativeLayout rlshy;//送货员
    private EditText remark;//备注
    private WiperSwitch wsfONOFF;//是否安装
    private RelativeLayout rlyjazsj;//预计安装时间
    private View viewline;//预计安装时间上面那条线
    private ListView daisongdetail;//商品明细
    private Button trans_save;//派工按钮
    private Dialog dialog;
    private String _phone = "13713713713";//客户的电话号码
    private String _phone2 = "13713713713";//d导购员的电话号码
    private DeliverDetailAdpter adpter;// 商品明细
    private DeliverDetail data;//明细数据源
    private FloatingActionButton fab;
    private TextView tv1;//预约送货时间
    private TextView tv10;//预计安装时间
    private String estimatedDeliveryTime;//预约送货时间的真实时间
    private String scheduledInstTime;// 预计安装时间的真实时间
    private TextView tv6;//送货员
    private boolean isBackBtn;//是否是在点击了返回按钮后弹出dialog
    public static int CALL_RESULT = -3;
    private String dlvid = "";//当前详细的主id
    private DeliverDPG.Datas.DeliverDPGListData singleData;

    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        rl_root = View.inflate(DeliverAppointmentActivity.this,
                R.layout.activity_deliver_appointment, null);
        setContentView(rl_root);
        mActivity = DeliverAppointmentActivity.this;

        singleData = (DeliverDPG.Datas.DeliverDPGListData) getIntent().getSerializableExtra("singleData");
        if (singleData != null) {
            dlvid = singleData.dlvid;
        }
        initview();
        initSystemCode();
        setDataHead();
        getGoodsList();
    }

    private void initview() {
        deliversname = (TextView) findViewById(R.id.deliversname);
        deliver_phone_call = (ImageView) findViewById(R.id.deliver_phone_call);
        deliver_send_sms = (ImageView) findViewById(R.id.deliver_send_sms);
        deliver_item_location = (TextView) findViewById(R.id.deliver_item_location);
        deliver_dgy = (TextView) findViewById(R.id.deliver_dgy);
        deliver_phone_call2 = (ImageView) findViewById(R.id.deliver_phone_call2);
        deliver_send_sms2 = (ImageView) findViewById(R.id.deliver_send_sms2);
        kdtime = (TextView) findViewById(R.id.kdtime);
        rlyytime = (RelativeLayout) findViewById(R.id.rlyytime);
        rlshy = (RelativeLayout) findViewById(R.id.rlshy);
        remark = (EditText) findViewById(R.id.remark);
        wsfONOFF = (WiperSwitch) findViewById(R.id.wsfONOFF);
        rlyjazsj = (RelativeLayout) findViewById(R.id.rlyjazsj);
        viewline = (View) findViewById(R.id.viewline);
        daisongdetail = (ListView) findViewById(R.id.daisongdetail);
        trans_save = (Button) findViewById(R.id.trans_save);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(DeliverAppointmentActivity.this, DeliverPGTripActivity.class));
            }

            ;
        });
        tv1 = (TextView) findViewById(R.id.tv1);
        tv10 = (TextView) findViewById(R.id.tv10);
        tv6 = (TextView) findViewById(R.id.tv6);
    }

    //初始取系统参数
    private boolean ifMultSelPeople = false;//选中派工人员是否可以多选
    private void initSystemCode() {
        if (SystemCodes.getInstance().getCRM_DlvIstManCanSelMore().equals("")) {
            new SystemCodePresenter(new SystemCodePresenter.CallBack() {
                @Override
                public void onSingle(int type, boolean isSuccess, String data, String fullmsg) {
                    if (type == 102){
                        if(isSuccess && data != null && data.equals("1")) {
                            SystemCodes.getInstance().setCRM_DlvIstManCanSelMore("1");
                            ifMultSelPeople = true;
                        }else {
                            SystemCodes.getInstance().setCRM_DlvIstManCanSelMore("0");
                            ifMultSelPeople = false;
                        }
                    }
                }

                @Nullable
                @Override
                public void onMult(boolean isSuccess, String fullmsg) {

                }

            }).getOneSystemParams(Tokens.DSM_IFSHOWOTHERPOINT, 102, 0);
        }else {
            if (SystemCodes.getInstance().getCRM_DlvIstManCanSelMore().equals("1"))
                ifMultSelPeople = true;
            else
                ifMultSelPeople = false;
        }
    }

    @Override
    protected void initAction() {
        wsfONOFF.setOnChangedListener(this);
        deliver_phone_call.setOnClickListener(this);
        deliver_send_sms.setOnClickListener(this);
        deliver_phone_call2.setOnClickListener(this);
        deliver_send_sms2.setOnClickListener(this);
        rlyytime.setOnClickListener(this);
        rlyjazsj.setOnClickListener(this);
        rlshy.setOnClickListener(this);

        //根据后台返回的 是否需要安装 信息来判断是否打开开关
        if (singleData != null) {
            if (singleData.ifist.equals("0")) {
                wsfONOFF.setChecked(false);
                viewline.setVisibility(View.GONE);
                rlyjazsj.setVisibility(View.GONE);
                scheduledInstTime="";
                tv10.setText("请选择");
            } else if (singleData.ifist.equals("1")) {
                wsfONOFF.setChecked(true);
                viewline.setVisibility(View.VISIBLE);
                rlyjazsj.setVisibility(View.VISIBLE);
                scheduledInstTime = singleData.pidate;
                tv10.setText(changeDate(scheduledInstTime));
            }
        }
    }

    //转换时间到派工格式
    private String changeDate(String date) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf2 = new SimpleDateFormat("HH点mm分");
            Date d = (Date) sdf.parse(date);
            String s = DateTimePicker.beforNumDay(d, 0) + DateTimePicker.getWeekOfDate(d, 0 - 1) + " " + sdf2.format(d);
            return s;
        } catch (Exception e) {
            return date;
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.deliver_phone_call:
                if (isRightNumber(_phone)) {
                    dialog = AppDialog.createDialog(mActivity,
                            "[" + deliversname.getText() + "]", _phone, this, "");
                    dialog.show();
                }
                break;
            case R.id.deliver_send_sms:
                if (isRightNumber(_phone)) {
                    Uri uri = Uri.parse("smsto:" + _phone);
                    intent = new Intent(Intent.ACTION_SENDTO, uri);
                    startActivity(intent);
                }
                break;
            case R.id.deliver_phone_call2:
                if (isRightNumber(_phone2)) {
                    dialog = AppDialog.createDialog(mActivity,
                            "[" + deliversname.getText() + "]", _phone2, this, "");
                    dialog.show();
                }
                break;
            case R.id.deliver_send_sms2:
                if (isRightNumber(_phone2)) {
                    Uri uri = Uri.parse("smsto:" + _phone2);
                    intent = new Intent(Intent.ACTION_SENDTO, uri);
                    startActivity(intent);
                }
                break;
            case R.id.rlyytime:
                DateUtils.onYearMonthDayTimePicker(mActivity, 15, "预约时间", dateTimeListener1);
                break;
            case R.id.rlyjazsj:
                DateUtils.onYearMonthDayTimePicker(mActivity, 15, "预计时间", dateTimeListener2);
                break;
            case R.id.rlshy:
                SelectPeopleActivity.open(mActivity, 2, null, ifMultSelPeople);
                break;
            case R.id.ok:
                if (isBackBtn) {
                    mActivity.finish();
                } else {
                    try {
                        if (PermissionUtils.isCallPhoneGranted(mActivity)) {
                            intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
                                    + _phone));
                            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            mActivity.startActivity(intent);
                            dialog.dismiss();
                        } else {
                            PermissionUtils.ToSetPermissions(mActivity, R.string.PermissionsCallPhone);
                        }
                    } catch (Exception e) {
                        NLogger.e("" + e.getMessage());
                    }
                }
                break;
        }
    }

    @Override
    public void OnChanged(WiperSwitch wiperSwitch, boolean checkState) {
        // TODO Auto-generated method stub
        if (checkState) {
            viewline.setVisibility(View.VISIBLE);
            rlyjazsj.setVisibility(View.VISIBLE);
            if (singleData != null) {
                singleData.ifist = "1";
            }
        } else {
            viewline.setVisibility(View.GONE);
            rlyjazsj.setVisibility(View.GONE);
            if (singleData != null) {
                singleData.ifist = "0";
            }
        }

    }

    //预约时间
    DateTimePicker.OnYearMonthDayTimePickListener dateTimeListener1 = new DateTimePicker.OnYearMonthDayTimePickListener() {
        @Override
        public void onDateTimePicked(int index, String year) {
            //Toast.show(mActivity, "" + year, 2000);
            if (index == 0) {
                long nowDate = System.currentTimeMillis();
                Date d = new Date(nowDate);
                String s = year.replace("今天", (DateTimePicker.beforNumDay(d, 0) + DateTimePicker.getWeekOfDate(d, 0 - 1)));
                if (s.length() < 10) {
                    return;
                } else {
                    tv1.setText(s);
                    estimatedDeliveryTime = DateTimePicker.BackDateToTime(s);
                }
            } else {
                if (year.length() < 10) {
                    return;
                } else {
                    tv1.setText(year);
                    estimatedDeliveryTime = DateTimePicker.BackDateToTime(year);
                }
            }
        }
    };
    //预计时间
    DateTimePicker.OnYearMonthDayTimePickListener dateTimeListener2 = new DateTimePicker.OnYearMonthDayTimePickListener() {
        @Override
        public void onDateTimePicked(int index, String year) {
            //Toast.show(mActivity, "" + year, 2000);
            if (index == 0) {
                long nowDate = System.currentTimeMillis();
                Date d = new Date(nowDate);
                String s = year.replace("今天", (DateTimePicker.beforNumDay(d, 0) + DateTimePicker.getWeekOfDate(d, 0 - 1)));
                if (s.length() < 10) {
                    return;
                } else {
                    tv10.setText(s);
                    scheduledInstTime = DateTimePicker.BackDateToTime(s);
                }
            } else {
                if (year.length() < 10) {
                    return;
                } else {
                    tv10.setText(year);
                    scheduledInstTime = DateTimePicker.BackDateToTime(year);
                }
            }
        }
    };

    public void setDataHead() {
        if (singleData != null) {
            deliversname.setText(ConvertUtils.formatNullF(singleData.buildname) + ConvertUtils.formatNull(singleData.cstname));
            deliver_item_location.setText(ConvertUtils.formatNull(singleData.address) + "");
            kdtime.setText(ConvertUtils.formatNull(singleData.cdate) + "");
            _phone = singleData.cstmobile;
        }
    }

    // 获取送货商品列表
    public void getGoodsList() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "getdlvgoodslist");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("dlvid", dlvid);
        netManager.connectWork(params, NetManager.DELIVER_GOODSLIST);
    }

    //提交派工信息
    public void submitPGInfo() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "dlvassign");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("dlvid", dlvid);
        params.addBodyParameter("dlvman", MyApplication.selectID);
        params.addBodyParameter("pddate", estimatedDeliveryTime);
        params.addBodyParameter("ifist", singleData.ifist);
        params.addBodyParameter("pidate", singleData.ifist.equals("0") ? "" : scheduledInstTime);
        params.addBodyParameter("remark", remark.getText().toString());
        netManager.connectWork(params, NetManager.DELIVER_PGSUBMIT);
    }

    protected NetManager netManager = new NetManager() {
        @Override
        public void onNetWorkErorr(int code, String result) {
            Toast.show(mActivity, "请求失败:" + result, 2000);
        }

        @Override
        public void onNetWorkSuccess(int code, String result) {
            if (code == NetManager.DELIVER_GOODSLIST) {
                data = gson.fromJson(result, DeliverDetail.class);
                if (data.success) {
                    adpter = new DeliverDetailAdpter(mActivity, data);
                    daisongdetail.setAdapter(adpter);
                    daisongdetail.setDivider(null);

                    //重算高度
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.dpToPx(mActivity, 135) * data.data.size());
                    daisongdetail.setLayoutParams(params);
                }

            } else if (code == NetManager.DELIVER_PGSUBMIT) {
                ReturnMsgEntity reEntity = JsonUtil.returnMsgEntity(result);
                if (reEntity.getSuccess() && reEntity.getMsgcode()==0) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            setResult(DeliverPGActivity.REFLESH_DATA);
                            MyApplication.isNeedToReflash = true;
                            finish();
                        }
                    }, 2000);
                    AppDialog.showTaskingDialog(mActivity, R.drawable.send_success, "任务派送成功").show();
                } else {
                    String msg = reEntity.getMsg();
                    if(msg.equals("")) msg = "任务派送失败";
                    AppDialog.showTaskingDialog(mActivity, R.drawable.send_failure, msg).show();
                }
            }
        }
    };

//    //加载数据
//    private void initdata() {
//        data = new ArrayList<DeliverDetail>();
//        for (int i = 0; i < 5; i++) {
//            DeliverDetail dd = new DeliverDetail();
//            dd.setSpname("美式蜘蛛网龟背扶手椅");
//            dd.setSpguige("长636mm*宽618mm*高930mm");
//            dd.setSpshuliang("2");
//            dd.setSppic("http://shit.com");
//            data.add(dd);
//        }
//
//        adpter = new DeliverDetailAdpter(mActivity, data);
//        daisongdetail.setAdapter(adpter);
//        daisongdetail.setDivider(null);
//
//        //重算高度
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.dpToPx(mActivity, 135) * data.size());
//        daisongdetail.setLayoutParams(params);
//    }

    public void save(View view) {
        if (tv1.getText().equals("请选择")) {
            Toast.show(mActivity, "请选择预约送货时间", 2000);
            return;
        }
        if (tv6.getText().equals("请选择")) {
            Toast.show(mActivity, "请选择送货员", 2000);
            return;
        }

        if (singleData != null) {
            if (singleData.ifist.equals("1")) {
                if (tv10.getText().equals("请选择")) {
                    Toast.show(mActivity, "请选择预约安装时间", 2000);
                    return;
                }
            }
        }

        //如果是需要安装，则判断安装时间时候在送货时间之后
        if (singleData != null) {
            if (singleData.ifist.equals("1")) {
                if (TimeUtils.diffTime(estimatedDeliveryTime, scheduledInstTime,"yyyy-MM-dd HH:mm")) {

                } else {
                    Toast.show(mActivity, "预计安装时间不能小于预约送货时间", 2000);
                    return;
                }
            }
        }

        submitPGInfo();
    }

    @Override
    public void onBackViewClick(View view) {
        dialog = AppDialog.createEjectNoticeDialog(mActivity, this);
        isBackBtn = true;
        dialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            dialog = AppDialog.createEjectNoticeDialog(mActivity, this);
            isBackBtn = true;
            dialog.show();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String name = MyApplication.selectPeople;
        if (name != null) {
            tv6.setText(name + "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.selectID = "";
        MyApplication.selectPeople = "请选择";
    }
}
